import axios from '@/plugins/axios';

export async function fetchFile(fileUri: string, responseType: 'blob' | 'text' = 'blob'): Promise<string | Blob> {
  try {
    const response = await axios.get(`/api/file/${fileUri}`, {
      responseType: responseType === 'text' ? 'text' : 'blob',
    });
    if (responseType === 'text') {
      return response.data as string;
    }
    return URL.createObjectURL(response.data as Blob);
  } catch (error) {
    throw new Error('文件获取失败');
  }
}

export async function downloadFile(fileUri: string, fileName: string): Promise<void> {
  try {
    const response = await axios.get(`/api/file/${fileUri}`, {
      responseType: 'blob',
    });
    const blob = response.data as Blob;
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName || fileUri.split('/').pop() || 'download';
    a.click();
    URL.revokeObjectURL(url);
  } catch (error) {
    throw new Error('文件下载失败');
  }
}